/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rmatos.course.practices.web.primes.backend;

import com.rmatos.course.practices.web.primes.exceptions.PrimeLimitException;
import java.util.ArrayList;

/**
 *
 * @author rmatos
 */
public class PrimesCalculator {

    private String limit = "";

    public PrimesCalculator() {
    }

    public PrimesCalculator(String limit) {

        this.limit = limit;

    }

    public String getLimit() {

        return limit;
    }

    public void setLimit(String limit) {

        this.limit = limit;

    }

    public ArrayList<Integer> getPrimesNumbers() throws Exception {

        //You can handle this bussiness rule from UI using Javascript

        ArrayList<Integer> primes = new ArrayList<Integer>();
        boolean isPrime = true;

        try {

            int tempLimit = Integer.parseInt(limit);


            if (tempLimit <= 2) {

                throw new PrimeLimitException("Please specified a higher number");

            } else {

                for (int i = 2; i <= tempLimit; i++) {

                    for (int j = i - 1; j >= 2; j--) {


                        if (i % j == 0) {

                            isPrime = false;
                            break;
                        }


                    }


                    if (isPrime) {

                        primes.add(i);

                    } else {

                        isPrime = true;

                    }
                }


            }

        } catch (NumberFormatException nfe) {

            throw new NumberFormatException("Unable to parse. Please check the field");

        }


        return primes;

    }
}
